import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:get/get.dart'  hide MultipartFile, FormData;
import 'package:image_picker/image_picker.dart';
import 'package:xin_he/page/mine/xin_he_mine_real_name_auth/xin_he_auth_model_entity.dart';
import 'package:xin_he/page/mine/xin_he_mine_real_name_auth/xin_he_ocr_model_entity.dart';

import '../../../service/xin_he_reqest.dart';
import '../../../service/xin_he_url_class.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import '../../../utils/xin_he_user_data.dart';
import 'xin_he_mine_real_name_auth_state.dart';

class XinHeMineRealNameAuthLogic extends GetxController {
  final XinHeMineRealNameAuthState state = XinHeMineRealNameAuthState();

  // ImagePicker获取内容后返回的对象是XFile
  XFile? upImage;
  late File _upFile;
  XFile? downImage;
  late File _downFile;

  List<XFile>? imageList;
  XFile? video;
// 使用ImagePicker前必须先实例化
  final ImagePicker _imagePicker = ImagePicker();


  Rx<XinHeAuthModelEntity> authModel = XinHeAuthModelEntity().obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();


  }

  @override
  void onReady() {
    super.onReady();

    if(xinHeUserData.userDetailInfo.value?.identifying != null){
      if(xinHeUserData.userDetailInfo.value?.identifying == 1){
        requestRealNameInfo();
      }else {
        requestRealNameInfo();

      }
    }

  }

  requestRealNameInfo()async {

    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic>map = {
      'userId':userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/identity/findIdentityByUserId',params: map,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);

      return;
    }
    if( result.data['code'] == 0) {
       authModel.value = XinHeAuthModelEntity.fromJson(result.data['data']);
    }else {
      XinHeToast.center(result.data['message']);

    }

  }

  ///经营范围
  idNumChange(String value){
    state.idNum = value;
  }
  nameChange(String value){
    state.name = value;
  }
  phoneNumChange(String value){
    state.phoneNum = value;
  }

  ///是否勾选
  changeSelectedStatus() {
    state.selected.value = !state.selected.value;
    // setSaveButtonStatus();
  }

  selectedUpImage() async {
    XFile? image = await _imagePicker.pickImage(
      source: ImageSource.gallery,
      imageQuality: 90,
      // maxWidth: 2000,

    );
    if (image != null) {
      upImage = image;

      _upFile = File(image.path);
      List<int>  imageBytes = await _upFile!.readAsBytes();
      String base64 = base64Encode(imageBytes);
      String base64Image = "data:image/png;base64,$base64";



      Map<String,dynamic>map = {
        "image_base64":base64Image,
        'showapi_appid':'1461451',
        'showapi_sign':'f3db0ad667c24eb3802136702793802b',
      };
      String url = 'https://route.showapi.com/1872-1';
      XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: url,params: map,isPost: true,isPostAndwwwForm: true);

      if(!result.result){
        XinHeToast.center(result.data['message']);
        return ;
      }

      if(result.data['showapi_res_body']['code'] ==0){

        XinHeOcrModelEntity model = XinHeOcrModelEntity.fromJson(result.data['showapi_res_body']);

        state.upOcrModel.value = model;
      }else {
        XinHeToast.center(result.data['showapi_res_body']['msg']);

      }

      state.upImagePath.value = upImage!.path;


      uploadToAli(upImage!.path, true);


      // Map<String, dynamic> upMap = {};
      // var name = upImage!.path.substring(upImage!.path.lastIndexOf("/") + 1, upImage!.path.length);
      // upMap['file'] = await MultipartFile.fromFile(upImage!.path,filename: name);
      //
      //
      // FormData formData  = FormData.fromMap(upMap);
      //
      //
      // Dio dio = Dio(BaseOptions(
      //     headers: {'Content-Type': 'multipart/form-data;boundary=----------'}));
      // String urlss = "${XinHeHostUrlClass.hostUrl}/alibaba/uploadPhoto";
      // var res = await dio.post(urlss, data: formData);
      //
      //
      // dynamic dataObj;
      // if(res.statusCode == 200){
      //   if (res.data is Map) {
      //     dataObj = res.data;
      //   } else {
      //     dataObj = json.decode(res.data.toString()) ?? {};
      //   }
      //
      //   if(dataObj['code'] == 0){
      //
      //     String upUrl = dataObj['data'];
      //     state.upurl = upUrl;
      //   }
      //
      // }

    }
  }

  uploadToAli(String filePath, bool isUp) async{

    Map<String, dynamic> upMap = {};
    var name = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
    upMap['file'] = await MultipartFile.fromFile(filePath,filename: name);


    FormData formData  = FormData.fromMap(upMap);


    Dio dio = Dio(BaseOptions(
        headers: {'Content-Type': 'multipart/form-data;boundary=----------'}));
    String urlss = "${XinHeHostUrlClass.hostUrl}/alibaba/uploadPhoto";
    var res = await dio.post(urlss, data: formData);


    dynamic dataObj;
    if(res.statusCode == 200){
      if (res.data is Map) {
        dataObj = res.data;
      } else {
        dataObj = json.decode(res.data.toString()) ?? {};
      }

      if(dataObj['code'] == 0){

        String upUrl = dataObj['data'];

        if(isUp){
          state.upurl = upUrl;

        }else {
          state.downurl = upUrl;

        }
      }

    }

  }

  selecteDownImage() async {
    XFile? image = await _imagePicker.pickImage(
      source: ImageSource.gallery,
      imageQuality: 90

    );
    if (image != null) {
      downImage = image;

      _downFile = File(image.path);
      List<int>  imageBytes = await _downFile!.readAsBytes();
      String base64 = base64Encode(imageBytes);
      String base64Image = "data:image/png;base64,$base64";
      // Map<String,dynamic>map = {
      //   "image_base64":base64Image,
      //   'showapi_appid':'1461451',
      //   'showapi_sign':'f3db0ad667c24eb3802136702793802b',
      // };
      // String url = 'https://route.showapi.com/1872-1';
      // XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: url,params: map,isPost: true,isPostAndwwwForm: true);
      //
      // if(!result.result){
      //   XinHeToast.center(result.data['message']);
      //   return ;
      // }
      //
      // if(result.data['showapi_res_body']['code'] ==0){
      //   XinHeOcrModelEntity model = XinHeOcrModelEntity.fromJson(result.data['showapi_res_body']);
      //   state.downOcrModel.value = model;
      // }else {
      //   XinHeToast.center(result.data['showapi_res_body']['msg']);
      //
      // }

      state.downImagePath.value = downImage!.path;


     await  uploadToAli(downImage!.path, false);

    }
  }

  submitAction() async{

    // if(state.name.isEmpty){
    //   XinHeToast.center('请填写姓名');
    //   return;
    // }
    //
    // if(state.idNum.isEmpty){
    //   XinHeToast.center('请填写身份证号码');
    //   return;
    // }
    //
    // if(state.phoneNum.isEmpty){
    //   XinHeToast.center('请填写手机号');
    //   return;
    // }

    var userId =  await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic>map = {
      'card':state.upOcrModel.value.idcard,
      'certificateFront':state.upurl,
      'certificateBack':state.downurl,
      'gender':state.upOcrModel.value.sex,
      'name':state.upOcrModel.value.name,
      'userId': userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/identity/saveIdentity',params: map,isPost: true,isPostAndwwwForm: true);

    if(!result.result|| result.data['code'] != 0){
      XinHeToast.center(result.data['message']);
      return ;
    }

  }



}
